//
//  LCMobileLoginViewController.m
//  wan77h5
//
//  Created by jiukuyinyue on 2017/9/1.
//  Copyright © 2017年 LC. All rights reserved.
//

#import "LCMobileRegisteredViewController.h"
#import "LCLoginTextField.h"
#import "ViewController.h"
#import "zhOverflyView.h"
#import "zhPopupController.h"
#import "JPUSHService.h"

@interface LCMobileRegisteredViewController ()

@property (weak, nonatomic) IBOutlet UIButton *loginButton;

@property (weak, nonatomic) UITextField *userTextField;
@property (weak, nonatomic) UITextField *codeTextField;
@property (weak, nonatomic) IBOutlet UIImageView *userImageView;
@property (weak, nonatomic) IBOutlet UIImageView *codeImageView;

@property (weak, nonatomic) UIButton *codeButton;
@property (strong, nonatomic) zhOverflyView *overflyView;

@end

@implementation LCMobileRegisteredViewController{
    NSTimer         *_timer;
    NSInteger       _count;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"注册";
    self.view.backgroundColor = RGBColor(236, 236, 236);
    _loginButton.enabled = NO;//禁用
    [self setupLogin];
    
    [_userTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [_codeTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}
#pragma mark - 初始化布局
-(void)setupLogin{
    LCLoginTextField *userTextField = [[LCLoginTextField alloc] init];
    userTextField.font = [UIFont systemFontOfSize:15];
    userTextField.backgroundColor = [UIColor whiteColor];
    userTextField.borderStyle = UITextBorderStyleNone;
    userTextField.layer.borderColor = RGBColor(255, 255, 255).CGColor;
    userTextField.layer.borderWidth = 1;
    userTextField.layer.cornerRadius = 5;
    userTextField.keyboardType = UIKeyboardTypeNumberPad;
    userTextField.placeholder = @"手机号";
    userTextField.adjustsFontSizeToFitWidth = YES;//自适应大小
    
    _userTextField = userTextField;
    [self.view insertSubview:userTextField atIndex:0];
    
    LCLoginTextField *codeTextField = [[LCLoginTextField alloc] initWithFrame:CGRectMake(54, 300, 211, 30)];
    codeTextField.font = [UIFont systemFontOfSize:15];
    codeTextField.backgroundColor = [UIColor whiteColor];
    codeTextField.borderStyle = UITextBorderStyleNone;
    codeTextField.layer.borderColor = RGBColor(255, 255, 255).CGColor;
    codeTextField.layer.borderWidth = 1;
    codeTextField.layer.cornerRadius = 5;
    codeTextField.placeholder = @"请输入短信验证码";
    codeTextField.adjustsFontSizeToFitWidth = YES;
    codeTextField.secureTextEntry = YES;//输入*号显示

    _codeTextField = codeTextField;
    //    [self.view addSubview:codeTextField];
    [self.view insertSubview:codeTextField atIndex:0];
    
    UIButton *codeButton = [[UIButton alloc] init];
    _codeButton = codeButton;
    [codeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    //默认不能点击,输入手机号后可以点击
    [self isCodeButtonEnabled:NO];
    [codeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [codeButton addTarget:self action:@selector(clickCodeButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:codeButton];
    
    
    [_userImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(userTextField.mas_centerY);
        make.width.offset(22);
        make.left.offset(30);
    }];
    
    [userTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(104);
        make.left.equalTo(_userImageView.mas_left).offset(-8);
        make.right.offset(-30);
        
        make.height.offset(40);
    }];
    [_codeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(userTextField.mas_bottom).offset(20);
        make.width.offset(25);
        make.left.offset(30);
    }];
    [codeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_codeImageView.mas_left).offset(-6);
        make.right.offset(-30);
        make.centerY.equalTo(_codeImageView.mas_centerY);
        make.height.offset(40);
    }];
    [codeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(codeTextField.mas_right).offset(0);
        make.centerY.equalTo(codeTextField.mas_centerY);
        make.width.offset(120);
        make.height.offset(40);
    }];
    
    [_loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_codeTextField.mas_bottom).offset(20);
        make.left.equalTo(_codeTextField.mas_left).offset(0);
        make.right.equalTo(_codeTextField.mas_right).offset(0);
        make.height.equalTo(_codeTextField);
    }];
    
}

//设置codebutton的状态颜色
-(void)isCodeButtonEnabled:(BOOL)enabled{
    if (enabled == YES) {
        [_codeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        self.codeButton.userInteractionEnabled = YES;
    } else {
        [_codeButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        self.codeButton.userInteractionEnabled = NO;
    }
}
/**
 监听键盘是否 输入用户名 密码
 */
-(void)textFieldDidChange :(UITextField *)theTextField{
    
    if (_userTextField.text.length == 11 && _codeTextField.text.length == 6){
        _loginButton.enabled = YES;
    }else{
        _loginButton.enabled = NO;
    }
    
    if (_userTextField.text.length == 11 && _count == 0){
        [self isCodeButtonEnabled:YES];

    }else{
        [self isCodeButtonEnabled:NO];
        //图行验证码按钮不能点击
    }
    
}
- (void)dealloc {
    [self clearTimer];
}

- (void)clearTimer {
    if(_timer) {
        if([_timer isValid]) [_timer invalidate];
    }
    _timer = nil;
}
- (void)doTimer {
    _count --;
    
    if(_count > 0) {
        [self.codeButton setTitle:[NSString stringWithFormat:@"%zd后重新获取",_count] forState:UIControlStateNormal];
        [self isCodeButtonEnabled:NO];
    } else {
        [self clearTimer];
        [self.codeButton setTitle:@"重新获取" forState:UIControlStateNormal];
        if (_userTextField.text.length == 11){
            [self isCodeButtonEnabled:YES];
        }
    }
}

- (void)beginCodeTick {
    
    [self clearTimer];
    [_codeButton setTitle:@"60后重新获取" forState:UIControlStateNormal];
    [self isCodeButtonEnabled:NO];

    _count = 60;
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(doTimer) userInfo:nil repeats:YES];
}
- (void)clickCodeButton:(UIButton *)sender {
    
    if ([_userTextField.text isEqualToString:@""] || _userTextField.text.length != 11 ) {
        return;
    }
    //判断手机号是否正确isValidateMobile
//    BOOL checkMobile = [_userTextField.text isMobileNumber];
    BOOL checkMobile = [LSZSpecialPackaging isValidateMobile:_userTextField.text];

    if (checkMobile) {
        [self setCode];
 
    }else{
        [SVProgressHUD showErrorWithStatus:@"请输入正确手机号!"];
    }
}
#pragma mark - 弹出框
- (void)example3:(NSString *)qrYZMStr {
    zhOverflyView *overflyView = [self overflyView:qrYZMStr];
    
    zhOverflyButton *btn1 = [zhOverflyButton buttonWithTitle:@"取消" handler:^(zhOverflyButton * _Nonnull button) {
        [self.zh_popupController dismiss];
    }];
    [btn1 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    
    zhOverflyButton *btn2 = [zhOverflyButton buttonWithTitle:@"立即验证" handler:NULL];
    [btn2 setTitleColor:[UIColor r:236 g:78 b:39] forState:UIControlStateNormal];
    [btn2 addTarget:self action:@selector(clickMBCodeDuanXin:) forControlEvents:UIControlEventTouchUpInside];
    
    [overflyView adjoinWithLeftAction:btn1 rightAction:btn2];
    
    self.zh_popupController = [zhPopupController new];
    self.zh_popupController.dismissOnMaskTouched = NO;
    self.zh_popupController.dismissOppositeDirection = YES;
    self.zh_popupController.slideStyle = zhPopupSlideStyleFromBottom;
    [self.zh_popupController presentContentView:overflyView duration:0.75 springAnimated:YES];
}
- (zhOverflyView *)overflyView:(NSString *)qrYZMStr {
    
    NSString *msg = @" ";
    NSMutableAttributedString *attiMessage = [[NSMutableAttributedString alloc] initWithString:msg];
    NSString *text = [NSString stringWithFormat:@"请输入图形验证码"];
    NSMutableAttributedString *attiTitle = [[NSMutableAttributedString alloc] initWithString:text];
    
    //    CGFloat fac = 475; // 已知透明区域高度
    //    UIImage *image = [UIImage imageNamed:@"fire_arrow"];
    
    _overflyView = [[zhOverflyView alloc]
                    initWithFlyImage:nil
                    highlyRatio:0
                    attributedTitle:attiTitle
                    attributedMessage:attiMessage
                    yzm:qrYZMStr
                    constantWidth:280];
    
    
    _overflyView.layer.cornerRadius = 7;
    _overflyView.messageEdgeInsets = UIEdgeInsetsMake(10, 22, 10, 22);
    [_overflyView reloadAllComponents];
    return _overflyView;
}
#pragma mark  - 向后台发送请求 获取验证码
-(void)setCode
{
    NSDictionary *input = @{@"mobile":[NSString stringWithFormat:@"%@", _userTextField.text]};
    [kNetworkTool POSTFuYinWithUrlString:GET_MBCODE_URL input:input success:^(NSDictionary *responseObject) {
        if ([[NSString stringWithFormat:@"%@",responseObject[@"status"]] isEqualToString:@"1"]) {
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                [SVProgressHUD showSuccessWithStatus:@"获取短信验证码成功"];
                [self beginCodeTick];
            }];
        } else {
            [SVProgressHUD showErrorWithStatus:@"失败,请重新获取"];
        }
        
        
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络获取失败,请重新获取"];
        NSLog(@"error = %@", error);
    }];
}
#pragma mark -  yz短信验证码  -
- (void)clickMBCodeDuanXin:(UIButton *)sender {

    [self.zh_popupController dismiss];
    
    if (_overflyView.yzmTextField.text.length == 4) {
        NSDictionary *input = @{@"mobile":[NSString stringWithFormat:@"%@", _userTextField.text],
                                @"grcode":[NSString stringWithFormat:@"%@", _overflyView.yzmTextField.text],
                                };
        
        [kNetworkTool POSTFuYinWithUrlString:GET_MBCODE_URL input:input success:^(NSDictionary *responseObject) {
            if ([[NSString stringWithFormat:@"%@",responseObject[@"status"]] isEqualToString:@"1"]) {
                [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                    [SVProgressHUD showSuccessWithStatus:@"获取短信验证码成功"];
                    [self.view endEditing:YES];
                    [self beginCodeTick];
                }];
            } else {
                [SVProgressHUD showErrorWithStatus:@"失败,请重新获取"];
            }
            
            
        } failure:^(NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"网络获取失败,请重新获取"];
            NSLog(@"error = %@", error);
        }];
        
    }else{
        [SVProgressHUD showErrorWithStatus:@"请输入正确验证码"];
    }
}

/**
 登陆判断
 */
#pragma mark -  登陆判断  -
- (IBAction)clickLoginButton:(UIButton *)sender {
   
    
    if (_codeTextField.text.length == 6) {

    NSDictionary *input = @{@"mobile":[NSString stringWithFormat:@"%@", _userTextField.text],
                            @"code":[NSString stringWithFormat:@"%@", _codeTextField.text],
                            @"device":@"iOS",
                            @"incode":@""
                            };
        //登录的请求
    [kNetworkTool POSTFuYinWithUrlString:NEW_LOGIN_URL input:input success:^(NSDictionary *responseObject) {
        NSString * statusStr = [NSString stringWithFormat:@"%@",responseObject[@"status"]];
        if ([statusStr isEqualToString:@"1"]) {
            //存储数据
            [_UserM setMobileNum: _userTextField.text];
            [_UserM setUsercode:[NSString stringWithFormat:@"%@", responseObject[@"data"]]];
            [LSZRequestData getsStatisticsForMessagesNotRead:^(BOOL isOK, NSString * STRING, NSDictionary * dic) {
                if (isOK == YES) {
                    [_UserM setSys_not_read:dic[@"data"][@"sys_not_read"]];
                    [_UserM setMsg_not_read:dic[@"data"][@"msg_not_read"]];
                    NSNotification *notification =[NSNotification notificationWithName:@"ANewMessage" object:nil userInfo:nil];
                    [[NSNotificationCenter defaultCenter] postNotification:notification];
                    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ANewMessage" object:nil];
                }
            }];
            //在登录的地方也需要添加
            [JPUSHService setAlias:responseObject[@"data"] completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
                NSLog(@"%@",iAlias);
                if (iResCode == 0) {
                    NSLog(@"添加别名成功");
                }
            } seq:0];
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                
                UIStoryboard *sb = [UIStoryboard storyboardWithName:@"SetFindPwd" bundle:nil];
                UIViewController *controller = [sb instantiateInitialViewController];
                [self.navigationController pushViewController:controller animated:YES];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self loginSuccessAndloadShopData];
                });
            }];
        }else{
             [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
         }
     } failure:nil];
    }else{
        [SVProgressHUD showErrorWithStatus:@"请输入正确验证码"];
    }
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
@end
